<template>
  <ul>
    <template v-if="listStyle === 'plain'">
      <li v-for="attachment in attachments" :key="attachment.id">
        <slot :attachment="attachment">
          {{ attachment.fileName }}(
          <span
            style="color: #3598ff; cursor: pointer"
            @click="download(attachment.id, { fileName: attachment.fileName })"
            >下载</span
          >
          )
        </slot>
      </li>
    </template>
    <template v-if="listStyle === 'underline'">
      <li v-for="attachment in attachments" :key="attachment.id" class="attachment-render-file-item">
        <slot :attachment="attachment">
          <span
            class="attachment-render-file-name"
            :title="attachment.fileName"
            @click="download(attachment.id, { fileName: attachment.fileName })"
            >{{ attachment.fileName }}</span
          >
          <i class="el-icon-close attachment-render-icon--delete" title="删除附件" @click="deleteFile(attachment)"></i>
        </slot>
      </li>
    </template>
  </ul>
</template>

<script>
  import { findAllByParentUnid, download, remove } from '@/api/attachment/attachment'

  export default {
    name: 'AttachmentRender',
    props: {
      unid: String,
      listStyle: {
        type: String,
        default: 'plain'
      },
      value: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        attachments: []
      }
    },
    watch: {
      unid: {
        immediate: true,
        handler: 'fetchAttachments'
      },
      value: {
        immediate: true,
        handler(newVal) {
          this.attachments = newVal
        }
      }
    },
    methods: {
      download,
      async fetchAttachments() {
        if (this.unid) {
          const { data } = (await findAllByParentUnid(this.unid)) || {}
          this.attachments = data || []
        }
      },
      deleteFile(attachment) {
        this.$confirm('确认删除该附件吗？', '提示').then(async _ => {
          await remove(attachment.id)
          const index = this.attachments.findIndex(value => value.id === attachment.id)
          if (index > -1) {
            this.attachments.splice(index, 1)
          }
          this.$message.success('附件删除成功！')
        })
      }
    }
  }
</script>

<style lang="scss">
  .attachment-render-icon--delete {
    margin-left: 10px;
    cursor: pointer;

    &:hover {
      color: #f56c6c;
    }
  }

  .attachment-render-file-name {
    text-decoration: underline;
    cursor: pointer;

    @include ellipsis;

    &:hover {
      color: var(--color-primary);
    }
  }

  .attachment-render-file-item {
    display: flex;
    align-items: center;
    color: #808080;
  }
</style>
